
import unittest
import struct

import helper.serialize_helper as serialize_helper

class TestStruct(unittest.TestCase):
    def test_sample1(self):
        
        format = "=i5shf"
        self.assertEqual(15,struct.calcsize(format))
        
        int_value = -1
        str_value = "cheka"
        short_value = 100
        float_value = 3.14
        
        binimage = struct.pack(format,int_value,str_value,short_value,float_value)
        
        parsed = struct.unpack(format,binimage)
        self.assertTrue(isinstance(parsed,tuple))
        
        self.assertEqual(int_value,parsed[0])
        self.assertEqual(str_value,parsed[1])
        self.assertEqual(short_value,parsed[2])
        self.assertAlmostEqual(float_value,parsed[3],4)
        
    def test_str_characters(self):
        """
        demonstrate the difference between string and multiple characters
        """
        # ------------------------ when unpacked with "=5s",result is (string,) 
        src_string = "cheka"
        str_format = "="+str(len(src_string))+"s"
        
        binimage = struct.pack(str_format,src_string)
        # pay attention to that ",", because unpack always return a tuple, though it has only one item in this case
        cpy_string, = struct.unpack(str_format,binimage) 
        
        self.assertTrue(isinstance(cpy_string,str))
        self.assertEqual(src_string,cpy_string)
        
        # ------------------------ when unpacked with "=5c",result is a tuple of multiple characters 
        # ------------------------ (in python, just one-character string) 
        chars_format = "="+str(len(src_string)) + "c"
        chars_tuple = struct.unpack(chars_format,binimage)
        
        self.assertTrue(isinstance(chars_tuple,tuple))
        self.assertEqual(list(chars_tuple),[x for x in src_string])
        
    def test_serialize_string(self):
        src_string = "cheka"
        binimage = serialize_helper.pack_string(src_string)
        (cpy_string,offset) = serialize_helper.unpack_string(binimage,0)
        
        self.assertEqual(src_string,cpy_string)
        self.assertEqual(len(binimage),offset)
        
if __name__ == "__main__":
    unittest.main()